using System.Text.Json.Serialization;
using System.Text.Json;

namespace RestaurantFinder.Core.Models;

/// <summary>
/// 高德地图POI搜索API响应模型
/// </summary>
public class GaodePoiResponse
{
    [JsonPropertyName("status")]
    public string Status { get; set; } = string.Empty;

    [JsonPropertyName("count")]
    public string Count { get; set; } = string.Empty;

    [JsonPropertyName("info")]
    public string Info { get; set; } = string.Empty;

    [JsonPropertyName("pois")]
    public List<GaodePoi> Pois { get; set; } = new();
}

/// <summary>
/// 高德地图POI信息模型
/// </summary>
public class GaodePoi
{
    [JsonPropertyName("id")]
    public string Id { get; set; } = string.Empty;

    [JsonPropertyName("name")]
    public string Name { get; set; } = string.Empty;

    [JsonPropertyName("type")]
    public string Type { get; set; } = string.Empty;

    [JsonPropertyName("address")]
    public string Address { get; set; } = string.Empty;

    [JsonPropertyName("location")]
    public string Location { get; set; } = string.Empty;

    /// <summary>
    /// 电话号码 - 使用JsonElement处理字符串或空数组
    /// </summary>
    [JsonPropertyName("tel")]
    public JsonElement TelElement { get; set; }

    [JsonPropertyName("distance")]
    public string Distance { get; set; } = string.Empty;

    /// <summary>
    /// 商业扩展信息 - 使用JsonElement处理对象或空数组
    /// </summary>
    [JsonPropertyName("biz_ext")]
    public JsonElement BizExtElement { get; set; }

    /// <summary>
    /// 获取电话号码字符串
    /// </summary>
    public string GetTel()
    {
        try
        {
            // 如果是字符串类型，直接返回
            if (TelElement.ValueKind == JsonValueKind.String)
            {
                return TelElement.GetString() ?? string.Empty;
            }
            // 如果是数组类型，尝试获取第一个元素
            else if (TelElement.ValueKind == JsonValueKind.Array)
            {
                var array = TelElement.EnumerateArray().ToList();
                if (array.Count > 0 && array[0].ValueKind == JsonValueKind.String)
                {
                    return array[0].GetString() ?? string.Empty;
                }
            }
            return string.Empty;
        }
        catch
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 获取商业扩展信息
    /// </summary>
    public GaodeBizExt? GetBizExt()
    {
        try
        {
            // 如果是对象类型，尝试反序列化
            if (BizExtElement.ValueKind == JsonValueKind.Object)
            {
                return JsonSerializer.Deserialize<GaodeBizExt>(BizExtElement.GetRawText());
            }
            // 如果是数组或其他类型，返回null
            return null;
        }
        catch
        {
            return null;
        }
    }
}

/// <summary>
/// 高德地图商业扩展信息
/// </summary>
public class GaodeBizExt
{
    [JsonPropertyName("rating")]
    public string? Rating { get; set; }

    [JsonPropertyName("cost")]
    public string? Cost { get; set; }
} 